import java.text.SimpleDateFormat;
import java.util.*;
import java.util.UUID;

public class TicketSellingFunction {
    private SeatsForSession seats;
    private static Map<UUID, Sales.TicketInfo> soldTickets = new HashMap<>();


    private void generateTicket(String movieName, String sessionTime, String seatNumber, double originalPrice, boolean isChildTicket) {
        UUID ticketId = UUID.randomUUID();
        Sales.TicketInfo ticket = new Sales.TicketInfo();
        ticket.movieName = movieName;
        ticket.sessionTime = sessionTime;
        ticket.seatNumber = seatNumber;
        ticket.originalPrice = originalPrice;
        // 修改为使用actualPrice字段存储实际支付金额
        ticket.actualPrice = isChildTicket ? originalPrice * 0.6 : originalPrice;
        ticket.isChildTicket = isChildTicket;
        ticket.sellingTime = new Date();
        ticket.isRefunded = false;
        ticket.refundAmount = 0; // 初始化退款金额

        soldTickets.put(ticketId, ticket);
        Sales.addSale(ticket);
        printTicket(ticket, ticketId);
    }
    // 删除内部TicketInfo类，完全使用Sales.TicketInfo

    // 修改printTicket方法参数类型
    private void printTicket(Sales.TicketInfo ticket, UUID ticketId) {
        System.out.println("\n==========================================");
        System.out.println("|               电子影票                   |");
        System.out.println("|----------------------------------------|");
        System.out.printf("| 影片：%-30s   |\n", ticket.movieName);
        System.out.printf("| 场次：%-30s     |\n", ticket.sessionTime);
        System.out.printf("| 座位：%-30s     |\n", ticket.seatNumber);
        System.out.printf("| 票号：%-30s     |\n", ticketId.toString().substring(0, 8).toUpperCase());
        System.out.println("|                                        |");
        System.out.printf("| 票价：%-30.2f     |\n", ticket.actualPrice); // 改为显示actualPrice
        System.out.printf("| 类型：%-30s  |\n", ticket.isChildTicket ? "儿童票（6折）" : "全价票");
        System.out.println("==========================================");
    }

    // 完整退票流程
    // 修改后的退票方法
    public void refundTicket(Scanner scanner) {
        System.out.println("\n=== 退票功能 ===");
        System.out.println("请输入电子票号（8位字符，如：828A57C8）");

        String input = scanner.nextLine().trim().toUpperCase();
        try {
            // 修改验证逻辑为8位字符
            if (input.isEmpty() || input.length() != 8) {
                System.out.println("错误：票号长度必须为8位字符");
                return;
            }

            // 在已售票中查找匹配的票号
            Optional<Map.Entry<UUID, Sales.TicketInfo>> ticketEntry = soldTickets.entrySet().stream()
                    .filter(e -> e.getKey().toString().substring(0, 8).equalsIgnoreCase(input))
                    .findFirst();

            if (!ticketEntry.isPresent()) {
                System.out.println("错误：无效的电子票号或该票已退！");
                return;
            }

            UUID ticketId = ticketEntry.get().getKey();
            Sales.TicketInfo ticket = ticketEntry.get().getValue(); // 修改为Sales.TicketInfo

            if (ticket == null) {
                System.out.println("错误：无效的电子票号或该票已退！");
                return;
            }

            long hoursBeforeShow = calculateHoursBeforeShow(ticket.sessionTime);
            if (hoursBeforeShow < 1) {
                System.out.println("电影即将上映，无法退票！");
                return;
            }

            double refundAmount = calculateRefundAmount(ticket.actualPrice, hoursBeforeShow); // 改为使用actualPrice
            executeRefund(ticketId, ticket, refundAmount);

        } catch (IllegalArgumentException e) {
            System.out.println("电子票号格式错误！请确认：");
            System.out.println("1. 必须为8位字母数字组合");
            System.out.println("2. 您输入的票号：" + input);
        }
    }

    // 退票金额计算规则
    private double calculateRefundAmount(double price, long hoursBeforeShow) {
        if (hoursBeforeShow < 1) {
            System.out.println("电影即将上映，无法退票！");
            return 0;
        } else if (hoursBeforeShow < 24) {
            System.out.println("提前1-24小时内退票，扣除10%手续费");
            return price * 0.9;
        } else {
            System.out.println("提前24小时以上退票，全额退款");
            return price;
        }
    }

    // 实际执行退票操作
    // 修改executeRefund方法参数类型
    // 修改退票方法确保标记退款状态
    private void executeRefund(UUID ticketId, Sales.TicketInfo ticket, double refundAmount) {
        // 添加退票前检查
        if (ticket.isRefunded) {
            System.out.println("错误：该票已退过！");
            return;
        }

        SeatsForSession seats = SeatsForSession.getSeatsBySession(findSessionByTime(ticket.sessionTime));

        if (seats != null) {
            seats.cancelSeat(ticket.seatNumber);
        }

        // 修改为更新refundAmount字段
        ticket.refundAmount = refundAmount;
        ticket.isRefunded = true;
        Sales.addRefund(ticket); // 现在这个方法会更新原记录
        soldTickets.remove(ticketId);

        System.out.println("退票成功！");
        System.out.println("退款金额: " + refundAmount + "元");
    }

    // 场次查询方法
    private Session findSessionByTime(String sessionTime) {
        if (sessionTime == null || sessionTime.trim().isEmpty()) {
            System.out.println("错误：场次时间为空");
            return null;
        }
        // 获取所有场次
        LinkedList<Session> sessions = Session.getSessionList();
        if (sessions == null || sessions.isEmpty()) {
            System.out.println("警告：没有可用的场次信息");
            return null;
        }
        // 精确匹配场次时间
        for (Session session : sessions) {
            if (session != null && sessionTime.equals(session.getStartTime())) {
                return session;
            }
        }
        // 模糊匹配（允许时间格式差异）
        for (Session session : sessions) {
            if (session != null && sessionTime.replace(" ", "").equals(session.getStartTime().replace(" ", ""))) {
                return session;
            }
        }
        System.out.println("警告：未找到场次时间 " + sessionTime + " 对应的场次信息");
        return null;
    }

    // 时间计算工具方法
    private long calculateHoursBeforeShow(String sessionTime) {
        if (sessionTime == null) {
            return -1;
        }
        try {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            Date showTime = format.parse(sessionTime);
            Date now = new Date();
            // 计算剩余时间（毫秒）
            long diff = showTime.getTime() - now.getTime();
            // 转换为小时
            return diff / (60 * 60 * 1000);
        } catch (Exception e) {
            System.out.println("场次时间格式错误：" + sessionTime);
            return -1;
        }
    }



    // 修改getSoldTickets方法返回类型
    public static Map<UUID, Sales.TicketInfo> getSoldTickets() {
        return soldTickets;
    }

    public void sellTicketProcess() {
        Scanner scanner = new Scanner(System.in);

        System.out.println("\n=== 票务操作 ===");
        System.out.println("1. 售票");
        System.out.println("2. 退票");
        System.out.print("请选择操作(1-2): ");

        int choice = scanner.nextInt();
        scanner.nextLine();

        if (choice == 1) {
            sellTicket(scanner);
        } else if (choice == 2) {
            refundTicket(scanner);
        } else {
            System.out.println("无效的选择！");
        }
    }

    // 添加sellTicket方法
    private void sellTicket(Scanner scanner) {
        System.out.println("\n=== 售票流程 ===");

        // 获取电影和场次信息
        System.out.println("请输入电影名称：");
        String movieName = scanner.nextLine();

        System.out.println("请输入场次时间(格式：yyyy-MM-dd HH:mm)：");
        String sessionTime = scanner.nextLine();

        Session session = findSessionByTime(sessionTime);
        if (session == null) {
            System.out.println("未找到匹配场次！");
            return;
        }

        // 选座流程
        SeatsForSession seats = SeatsForSession.getSeatsBySession(session);
        seats.displaySeatsInfo();

        System.out.println("请输入要选择的座位号(如A5)：");
        String seatNumber = scanner.nextLine().toUpperCase();

        if (!seats.bookSeat(seatNumber)) {
            System.out.println("选座失败！原因：座位可能已被预订或无效");
            return;
        }

        // 票价计算
        double originalPrice = session.getPrice();
        System.out.println("是否为儿童票？(y/n)");
        boolean isChildTicket = scanner.nextLine().equalsIgnoreCase("y");
        double finalPrice = isChildTicket ? originalPrice * 0.6 : originalPrice;

        System.out.printf("票面价格: %.2f元\n", originalPrice);
        System.out.printf("最终支付金额: %.2f元\n", finalPrice);

        // 确认购票
        System.out.println("确认购票？(y/n)");
        if (scanner.nextLine().equalsIgnoreCase("y")) {
            generateTicket(movieName, sessionTime, seatNumber, originalPrice, isChildTicket);
            System.out.println("售票成功！");
            seats.displaySeatMap();
        } else {
            seats.cancelSeat(seatNumber);
            System.out.println("已取消购票");
        }
    }
}










